package com.piper.core.aop;

import com.piper.core.RequestData;
import com.piper.core.RequestDataHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 对控制器调用过程中,提供一种RequestData便捷调用的aop
 */
@Aspect
@Order(500)
public class RequestDataAop {

    @Pointcut("execution(* *..controller.*.*(..))")
    public void cutService() {
    }

    @Around("cutService()")
    public Object sessionKit(ProceedingJoinPoint point) throws Throwable {
        Object[] params = point.getArgs();

        if (params != null && params.length > 0) {
            if (params[0] instanceof RequestData) {
                RequestData requestData = (RequestData) params[0];
                RequestDataHolder.put(requestData);
            }
        }

        boolean sign = true;

        try {
            return point.proceed();
        } catch (Exception exception) {
            sign = false;
            throw exception;
        } finally {
            if (sign) {
                RequestDataHolder.remove();
            }
        }
    }

}
